package cn.wcy.design_patterns.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * 应用程序上下文持有者
 * Application context holder.
 *
 * @author wcy
 * @date 2024/01/17
 */
public class ApplicationContextHolder<T> {

    /** 应用程序上下文 */
    private static ApplicationContext applicationContext;

    private ApplicationContextHolder() {
        // 防止外部实例化
    }

    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    /**
     * Get ioc container bean by type.
     */
    public static <T> T getBean(Class<T> clazz) {
        assertContextInjected();
        return applicationContext.getBean(clazz);
    }

    /**
     * Get ioc container bean by name.
     */
    public static Object getBean(String name) {
        assertContextInjected();
        return applicationContext.getBean(name);
    }

    /**
     * Get ioc container bean by name and type.
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        assertContextInjected();
        return applicationContext.getBean(name, clazz);
    }

    /**
     * Get a set of ioc container beans by type.
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
        assertContextInjected();
        return applicationContext.getBeansOfType(clazz);
    }

    /**
     * Find whether the bean has annotations.
     */
    public static <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) {
        assertContextInjected();
        return applicationContext.findAnnotationOnBean(beanName, annotationType);
    }

    /**
     * Check if the application context has been injected.
     */
    private static void assertContextInjected() {
        if (applicationContext == null) {
            throw new IllegalStateException("Application context has not been injected yet. Ensure ApplicationContextHolder is initialized.");
        }
    }
}
